package rbac.service.array;

import rbac.domain.dto.RoleDto;
import rbac.domain.entity.Dept;
import rbac.domain.entity.Role;
import rbac.domain.vo.RoleVo;
import rbac.domain.vo.Result;
import rbac.service.IDeptService;
import rbac.service.IRoleService;
import rbac.service.IUserService;
import rbac.util.SingletonFactory;
import rbac.view.DeptView;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 基于数值存储的业务层-角色管理模块
 */

public class RoleService extends BaseService<Role, RoleDto, RoleVo> implements IRoleService {

    private IUserService userService;

    private RoleService() {
        data = new Role[DATA_SIZE + 1];
        temp = new RoleVo[DATA_SIZE];
    } // 将构造函数声明为私有

    @Override
    public Role createEntity(RoleDto dto, int id){
        LocalDateTime now = LocalDateTime.now();
        return new Role(id, now, now, dto.name, dto.dataScope);
    }

    @Override
    // 将角色实体对象转换为角色视图对象
    public RoleVo convertToVo(Role role){
        // 通过类名直接调⽤，⽆需创建 RoleService类的实例
        return new RoleVo(role.getId(), role.createAt, role.updateAt, role.name, role.dataScope);
    }

    @Override
    public void updateEntity(RoleDto dto, Role role) {
        role.updateAt = LocalDateTime.now();
        role.name = dto.name; // 原来在实体类的数据 -->-替换-> 刚刚输入在dto类的数据
        role.dataScope = dto.dataScope;
    }

    @Override
    public Result delete(int id){
        if (!existsById(id)){
            return Result.failure("删除失败，不存在该数据");
        }

        if (userService == null) { //懒加载
            userService = SingletonFactory.getInstance(UserService.class);
        }
        if (userService.roleInUse(id)) {
            return Result.failure("删除失败，有⽤户属于该部⻔，不能删除");
        }

        // 将指定ID的角色数据置为 null，表示删除该数据
        data[id] = null;

        return Result.success("删除成功", null);
    }

}

